from fastapi import APIRouter,Depends,Request,HTTPException, status, Query
from novelapp.config.database import connect
from novelapp.models.models import Books
from pydantic import BaseModel
from novelapp.common.common import returnData
import json,httpx,time
from typing import Optional,List
from tqdm import tqdm



# 定义异步函数调用外部API
async def fetch_external_api(url: str, params: dict) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.get(url, params=params)
        response.raise_for_status()  # 如果响应状态不是200，抛出HTTP异常
        return response.json()

    
router = APIRouter()  
# 15730 * 20
@router.get("/get_book/")
async def get_book():

    params = {}
    millis = int(round(time.time() * 1000))    
    params['t'] = millis 
    
    allbooks = Books.objects.count()
    page_num = allbooks // 20 + 5
    
    # return page_num
    
    for page in tqdm(range(page_num, 15830 + 1), desc="Processing pages", unit="page"):
        params['page'] = page
        url = "https://api.yousuu.com/api/bookStore/books"
        data = await fetch_external_api(url,params)

        if data.get("success"):
            booksData = data["data"]["books"]
            for book in booksData:  

                # print(book)
                bookRes = Books.objects(ysbookId=book["bookId"]).first()
                # print(bookRes)
                if not bookRes:
                    new_book = Books(
                        ysbookId=book["bookId"],  # 替换字段名
                        **{k: v for k, v in book.items() if k != "bookId"}  # 其他字段保持不变
                    )
                    # print(new_book)
                    
                    new_book.save()
                
        
        # print(data)
    

@router.get("/test/")
async def test(
    request: Request,
    sort: Optional[str] = Query(None),
    status: Optional[int] = Query(None),
    countWord: Optional[int] = Query(None),
    channel: Optional[int] = Query(None),
    classId: Optional[int] = Query(None),
    page: int = 1
    ):
        
    params = {}
    millis = int(round(time.time() * 1000))    
    params['t'] = millis 
    
    allbooks = Books.objects.count()
    page_num = allbooks // 20 + 5
    
    return page_num   
        
        
    try:
        data = await request.json()
    except json.JSONDecodeError:
        if await request.body() == b'':
            data = {}
        else:
            raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid JSON body")

    
    channel = data.get('channel',channel)
    classId = data.get('classId',classId)
    status = data.get('status',status)
    countWord = data.get('countWord',countWord)
    sort = data.get('sort',sort)
    page = data.get('page',page)
    
    params = {}
    # 只有当参数存在时才添加到params中
    if channel is not None:
        params['channel'] = channel
    if classId is not None:
        params['classId'] = classId
    if status is not None:
        params['status'] = status
    if countWord is not None:
        params['countWord'] = countWord
    if sort is not None:
        params['sort'] = sort
    if page is not None:
        params['page'] = page
        
    millis = int(round(time.time() * 1000))    
    params['t'] = millis 
    url = "https://api.yousuu.com/api/bookStore/books"
    try:
        # 调用异步函数获取数据
        data = await fetch_external_api(url,params)
        return data
    except httpx.RequestError as e:
        # 处理请求错误
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        # 处理其他可能的错误
        raise HTTPException(status_code=500, detail="An error occurred while fetching data")        

